package com.lms.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-08-21 08:48
 * @Description:
 */
public class DistributedClient {
    private static final String CONNECTION_STRING = "192.168.189.100:2181,192.168.189.101:2181,192.168.189.102:2181";
    private static final int SESSION_TIMEOUT = 2000;
    private ZooKeeper zk = null;
    private volatile ArrayList<String> serverList=new ArrayList<String>();


    /**
     * @Author 李孟帅
     * @Description 获取客户端连接
     * @Date 2020/8/20
     **/
    public void getConnection() throws IOException {
        zk = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    getServerList();
                } catch (KeeperException | InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
    * @Author 李孟帅
    * @Description 获取服务器列表
    * @Date 2020/8/21
    **/
    public void getServerList() throws KeeperException, InterruptedException {
        //获取子节点信息，并监听父节点
        List<String> children = zk.getChildren("/servers", true);
        ArrayList<String> servers = new ArrayList<>();
        for (String child : children) {
            byte[] data = zk.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }
        serverList=servers;
        System.out.println(serverList);
    }
    //业务功能
    public void handleBusiness() throws InterruptedException {
        System.out.println("client start working...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        //获取zk连接
        DistributedClient distributedClient = new DistributedClient();
        distributedClient.getConnection();
        //获取/servers子节点信息（并监听），从中获取服务器列表
        distributedClient.getServerList();
        //业务功能
        distributedClient.handleBusiness();
    }
}
